package com.ruoyi.system.service.impl;

import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.SysWechatAuth;
import com.ruoyi.system.domain.SysWechatConfig;
import com.ruoyi.system.mapper.SysWechatAuthMapper;
import com.ruoyi.system.mapper.SysWechatConfigMapper;
import com.ruoyi.system.service.IWechatAuthService;
import com.ruoyi.system.service.ISysUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.HashMap;
import java.util.Map;

/**
 * 微信授权服务实现
 * 
 * @author ruoyi
 * @date 2025-01-12
 */
@Service
public class WechatAuthServiceImpl implements IWechatAuthService 
{
    private static final Logger log = LoggerFactory.getLogger(WechatAuthServiceImpl.class);

    @Autowired
    private SysWechatConfigMapper wechatConfigMapper;

    @Autowired
    private SysWechatAuthMapper wechatAuthMapper;

    @Autowired
    private ISysUserService userService;

    private final RestTemplate restTemplate = new RestTemplate();

    // 微信API地址
    private static final String WECHAT_API_URL = "https://api.weixin.qq.com/sns/jscode2session";

    @Override
    public SysWechatConfig getWechatConfig()
    {
        SysWechatConfig config = wechatConfigMapper.selectWechatConfigById(1L);
        if (config == null)
        {
            log.error("微信配置未找到，请检查数据库中的sys_wechat_config表");
        }
        else
        {
            log.info("获取到微信配置: AppID={}, AppSecret={}", config.getAppId(), 
                    config.getAppSecret() != null ? "***" + config.getAppSecret().substring(config.getAppSecret().length() - 4) : "null");
        }
        return config;
    }

    @Override
    public Map<String, Object> getWechatUserInfo(String code)
    {
        SysWechatConfig config = getWechatConfig();
        if (config == null)
        {
            throw new RuntimeException("微信配置未找到");
        }

        String url = WECHAT_API_URL + "?appid=" + config.getAppId() + 
                    "&secret=" + config.getAppSecret() + 
                    "&js_code=" + code + 
                    "&grant_type=authorization_code";

        try
        {
            // 使用String接收响应，然后手动解析JSON
            String responseStr = restTemplate.getForObject(url, String.class);
            log.info("微信API原始响应: {}", responseStr);

            if (responseStr == null || responseStr.trim().isEmpty())
            {
                throw new RuntimeException("微信API返回空响应");
            }

            // 手动解析JSON响应
            ObjectMapper objectMapper = new ObjectMapper();
            @SuppressWarnings("unchecked")
            Map<String, Object> response = objectMapper.readValue(responseStr, Map.class);
            log.info("微信API解析后响应: {}", response);

            if (response != null && response.containsKey("errcode"))
            {
                Integer errcode = (Integer) response.get("errcode");
                if (errcode != null && errcode != 0)
                {
                    String errmsg = (String) response.get("errmsg");
                    throw new RuntimeException("微信API调用失败: " + errmsg);
                }
            }

            return response;
        }
        catch (Exception e)
        {
            log.error("调用微信API失败", e);
            throw new RuntimeException("获取微信用户信息失败: " + e.getMessage());
        }
    }

    @Override
    public SysUser selectUserByOpenid(String openid)
    {
        return userService.selectUserByOpenid(openid);
    }

    @Override
    public SysUser createWechatUser(Map<String, Object> wechatUserInfo)
    {
        String openid = (String) wechatUserInfo.get("openid");
        String sessionKey = (String) wechatUserInfo.get("session_key");
        String unionid = (String) wechatUserInfo.get("unionid");

        // 创建新用户
        SysUser user = new SysUser();
        user.setUserName("wx_" + openid.substring(0, Math.min(openid.length(), 20))); // 生成用户名
        user.setNickName("微信用户");
        user.setWechatOpenid(openid);
        user.setWechatUnionid(unionid);
        user.setUserType("01"); // 微信用户（复用现有字段）
        user.setStatus("0"); // 正常状态
        user.setDelFlag("0"); // 未删除
        user.setCreateBy("system");
        user.setCreateTime(DateUtils.getNowDate());
        user.setLoginCount(1);
        user.setLastLoginTime(DateUtils.getNowDate());

        // 插入用户
        userService.insertUser(user);

        // 为新用户分配普通角色（role_id = 2）
        userService.insertUserAuth(user.getUserId(), new Long[]{2L});

        // 保存微信授权记录
        SysWechatAuth wechatAuth = new SysWechatAuth();
        wechatAuth.setOpenid(openid);
        wechatAuth.setUnionid(unionid);
        wechatAuth.setSessionKey(sessionKey);
        wechatAuth.setUserId(user.getUserId());
        wechatAuth.setAuthTime(DateUtils.getNowDate());
        wechatAuth.setLastAuthTime(DateUtils.getNowDate());
        wechatAuth.setStatus("0");
        wechatAuth.setCreateTime(DateUtils.getNowDate());

        saveWechatAuth(wechatAuth);

        return user;
    }

    @Override
    public int saveWechatAuth(SysWechatAuth wechatAuth)
    {
        wechatAuth.setCreateTime(DateUtils.getNowDate());
        
        // 先查询是否已存在该openid的记录
        SysWechatAuth existingAuth = selectWechatAuthByOpenid(wechatAuth.getOpenid());
        if (existingAuth != null)
        {
            // 如果存在，则更新记录
            existingAuth.setSessionKey(wechatAuth.getSessionKey());
            existingAuth.setUnionid(wechatAuth.getUnionid());
            existingAuth.setUserId(wechatAuth.getUserId());
            existingAuth.setLastAuthTime(DateUtils.getNowDate());
            existingAuth.setUpdateTime(DateUtils.getNowDate());
            return updateWechatAuth(existingAuth);
        }
        else
        {
            // 如果不存在，则插入新记录
            return wechatAuthMapper.insertWechatAuth(wechatAuth);
        }
    }

    @Override
    public int updateWechatAuth(SysWechatAuth wechatAuth)
    {
        wechatAuth.setUpdateTime(DateUtils.getNowDate());
        return wechatAuthMapper.updateWechatAuth(wechatAuth);
    }

    @Override
    public SysWechatAuth selectWechatAuthByOpenid(String openid)
    {
        return wechatAuthMapper.selectWechatAuthByOpenid(openid);
    }

    @Override
    public Map<String, Object> wechatLogin(String code)
    {
        Map<String, Object> result = new HashMap<>();

        try
        {
            // 1. 通过code获取微信用户信息
            Map<String, Object> wechatUserInfo = getWechatUserInfo(code);
            String openid = (String) wechatUserInfo.get("openid");
            String sessionKey = (String) wechatUserInfo.get("session_key");

            if (StringUtils.isEmpty(openid))
            {
                throw new RuntimeException("获取微信openid失败");
            }

            // 2. 查询用户是否存在
            SysUser user = selectUserByOpenid(openid);
            
            // 添加日志：检查查询结果
            if (user == null)
            {
                log.info("通过openid查询用户不存在，openid: {}", openid);
                // 3. 用户不存在，创建新用户
                user = createWechatUser(wechatUserInfo);
                result.put("isNewUser", true);
                log.info("创建新用户成功，userId: {}, userName: {}", user.getUserId(), user.getUserName());
            }
            else
            {
                log.info("通过openid查询到已存在用户，userId: {}, userName: {}, wechatNickname: {}, wechatAvatar: {}", 
                        user.getUserId(), user.getUserName(), user.getWechatNickname(), user.getWechatAvatar());
                // 4. 用户存在，更新登录信息
                updateUserLoginInfo(user.getUserId());
                result.put("isNewUser", false);
                
                // 5. 更新微信授权记录（用户已存在时）
                SysWechatAuth wechatAuth = selectWechatAuthByOpenid(openid);
                if (wechatAuth != null)
                {
                    // 更新现有记录
                    wechatAuth.setSessionKey(sessionKey);
                    wechatAuth.setLastAuthTime(DateUtils.getNowDate());
                    updateWechatAuth(wechatAuth);
                }
                else
                {
                    // 如果授权记录不存在，创建新的授权记录
                    wechatAuth = new SysWechatAuth();
                    wechatAuth.setOpenid(openid);
                    wechatAuth.setUnionid((String) wechatUserInfo.get("unionid"));
                    wechatAuth.setSessionKey(sessionKey);
                    wechatAuth.setUserId(user.getUserId());
                    wechatAuth.setAuthTime(DateUtils.getNowDate());
                    wechatAuth.setLastAuthTime(DateUtils.getNowDate());
                    wechatAuth.setStatus("0");
                    wechatAuth.setCreateTime(DateUtils.getNowDate());
                    saveWechatAuth(wechatAuth);
                }
            }

            // 6. 生成登录token（这里需要调用现有的token生成逻辑）
            // 由于若依框架的token生成比较复杂，这里先返回用户信息
            // 实际使用时需要调用SysLoginService的login方法

            result.put("success", true);
            result.put("user", user);
            result.put("openid", openid);
            result.put("sessionKey", sessionKey);

            return result;
        }
        catch (Exception e)
        {
            log.error("微信登录失败", e);
            result.put("success", false);
            result.put("error", e.getMessage());
            return result;
        }
    }

    @Override
    public int updateUserLoginInfo(Long userId)
    {
        SysUser user = userService.selectUserById(userId);
        if (user != null)
        {
            user.setLastLoginTime(DateUtils.getNowDate());
            user.setLoginCount(user.getLoginCount() != null ? user.getLoginCount() + 1 : 1);
            return userService.updateUser(user);
        }
        return 0;
    }
}
